<template>
  <div class="json-editor">
    <textarea ref="textarea" />
  </div>
</template>

<script>
import CodeMirror from 'codemirror'
import 'codemirror/addon/lint/lint.css'
import 'codemirror/lib/codemirror.css'
import 'codemirror/theme/rubyblue.css'
import 'codemirror/mode/javascript/javascript'
import 'codemirror/addon/lint/lint'
import 'codemirror/addon/lint/json-lint'
require('script-loader!jsonlint')

export default {
  name: 'JsonEditor',
  props: {
		value: {
			required: true,
			type: String
		}
	},
  data() {
    return {
      jsonEditor: null
    }
  },
  watch: {
    value(value) {
      const editorValue = this.jsonEditor.getValue()
      if (value !== editorValue) {
        this.jsonEditor.setValue(JSON.stringify(this.value, null, 2))
      }
    }
  },
  mounted() {
    this.jsonEditor = CodeMirror.fromTextArea(this.$refs.textarea, {
      lineNumbers: true,
      mode: 'application/json',
      gutters: ['CodeMirror-lint-markers'],
      theme: 'rubyblue',
			lint: true,
			autoRefresh: true
		})
    this.jsonEditor.setValue(JSON.stringify(this.value, null, 2))
    this.jsonEditor.on('change', cm => {
			this.$emit('changed', cm.getValue())
			this.$emit('input', cm.getValue())
		})

		// codemirror 会有一个不刷新就不显示的问题, 这里定时刷新.
		setInterval(this.refresh, 1000)
	},

	methods: {
		refresh() {
        /*
         * refresh: Fires when the editor is refreshed or resized.
         * Mostly useful to invalidate cached values that depend on the editor or character size.
         */
				this.jsonEditor && this.jsonEditor.refresh();
      }
	}
}
</script>

<style lang="scss" scoped>
.json-editor {
  height: 100%;
  position: relative;
	box-shadow: 0 2px 4px rgba(0, 0, 0, .12), 0 0 6px rgba(0, 0, 0, .04);
  ::v-deep {
    .CodeMirror {
      height: auto;
      min-height: 300px;
    }
    .CodeMirror-scroll {
      min-height: 300px;
    }
    .cm-s-rubyblue span.cm-string {
      color: #F08047;
    }
  }
}
</style>
